import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Hash, Zap, AlertCircle, CheckCircle2 } from 'lucide-react';

interface DataInputModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (preImage: string) => Promise<boolean>;
  currentPreImage?: string;
}

export function DataInputModal({ isOpen, onClose, onSubmit, currentPreImage }: DataInputModalProps) {
  const [preImage, setPreImage] = useState(String(currentPreImage || ''));
  const [isGenerating, setIsGenerating] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);

  // 更新preImage当currentPreImage变化时
  useEffect(() => {
    setPreImage(String(currentPreImage || ''));
  }, [currentPreImage]);

  const validateInput = (value: string): string | null => {
    if (!value.trim()) {
      return '请输入原始数据';
    }
    
    // 检查是否为有效数字
    const num = Number(value.trim());
    if (isNaN(num)) {
      return '请输入有效的数字';
    }
    
    if (num < 0) {
      return '请输入非负数';
    }
    
    if (!Number.isInteger(num)) {
      return '请输入整数';
    }
    
    // 检查是否在合理范围内（避免过大的数字）
    if (num > Number.MAX_SAFE_INTEGER) {
      return '数字过大，请输入较小的值';
    }
    
    return null;
  };

  const handleSubmit = async () => {
    const validation = validateInput(preImage);
    if (validation) {
      setError(validation);
      return;
    }

    setIsGenerating(true);
    setError('');
    setSuccess(false);

    try {
      // 确保传递的是字符串
      const trimmedPreImage = String(preImage).trim();
      console.log('Submitting preImage:', trimmedPreImage, 'type:', typeof trimmedPreImage);
      
      const result = await onSubmit(trimmedPreImage);
      if (result) {
        setSuccess(true);
        setTimeout(() => {
          onClose();
          setSuccess(false);
        }, 1500);
      } else {
        setError('数据生成失败，请重试');
      }
    } catch (err) {
      setError('生成过程中出现错误');
      console.error('Data generation error:', err);
    } finally {
      setIsGenerating(false);
    }
  };

  const handleInputChange = (value: string) => {
    setPreImage(value);
    setError('');
    setSuccess(false);
  };

  const generateRandomData = () => {
    const randomValue = Math.floor(Math.random() * 1000000) + 100000; // 6位数字
    setPreImage(randomValue.toString());
    setError('');
    setSuccess(false);
  };

  const getExampleData = () => {
    const examples = ['888888', '123456', '999999', '666666', '111111'];
    return examples[Math.floor(Math.random() * examples.length)];
  };

  if (!isOpen) return null;

  return (
    <AnimatePresence>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        className="flex items-center justify-center p-4"
        onClick={onClose}
        style={{ 
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.6)',
          backdropFilter: 'blur(4px)',
          zIndex: 999999,
          pointerEvents: 'auto'
        }}
      >
        <motion.div
          initial={{ opacity: 0, scale: 0.9, y: 20 }}
          animate={{ opacity: 1, scale: 1, y: 0 }}
          exit={{ opacity: 0, scale: 0.9, y: 20 }}
          transition={{ type: "spring", damping: 25, stiffness: 500 }}
          className="bg-slate-800 rounded-xl shadow-2xl max-w-md w-full border border-slate-700"
          onClick={(e) => e.stopPropagation()}
        >
          {/* Header */}
          <div className="flex items-center justify-between p-6 border-b border-slate-700">
            <div className="flex items-center space-x-3">
              <div className="w-10 h-10 bg-quantum-blue/20 rounded-lg flex items-center justify-center">
                <Hash className="w-5 h-5 text-quantum-blue" />
              </div>
              <div>
                <h3 className="text-xl font-semibold text-white">自定义原始数据</h3>
                <p className="text-sm text-gray-400">输入您的秘密数据进行零知识证明</p>
              </div>
            </div>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-white transition-colors"
            >
              <X size={24} />
            </button>
          </div>

          {/* Content */}
          <div className="p-6 space-y-6">
            {/* Input Section */}
            <div className="space-y-3">
              <label className="block text-sm font-medium text-gray-300">
                原始数据 (preImage)
              </label>
              <div className="relative">
                <input
                  type="text"
                  value={preImage}
                  onChange={(e) => handleInputChange(e.target.value)}
                  placeholder="请输入数字，例如：888888"
                  className={`w-full px-4 py-3 bg-slate-700 border rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 transition-colors ${
                    error
                      ? 'border-red-500 focus:ring-red-500/50'
                      : success
                      ? 'border-green-500 focus:ring-green-500/50'
                      : 'border-slate-600 focus:ring-quantum-blue/50 focus:border-quantum-blue'
                  }`}
                  disabled={isGenerating}
                />
                {success && (
                  <CheckCircle2 className="absolute right-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-green-500" />
                )}
              </div>
              {error && (
                <motion.div
                  initial={{ opacity: 0, y: -10 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="flex items-center space-x-2 text-red-400 text-sm"
                >
                  <AlertCircle size={16} />
                  <span>{error}</span>
                </motion.div>
              )}
            </div>

            {/* Quick Actions */}
            <div className="space-y-3">
              <div className="text-sm font-medium text-gray-300">快速操作</div>
              <div className="grid grid-cols-2 gap-3">
                <button
                  onClick={generateRandomData}
                  disabled={isGenerating}
                  className="px-4 py-2 bg-slate-700 hover:bg-slate-600 text-white rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed text-sm"
                >
                  🎲 随机生成
                </button>
                <button
                  onClick={() => handleInputChange(getExampleData())}
                  disabled={isGenerating}
                  className="px-4 py-2 bg-slate-700 hover:bg-slate-600 text-white rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed text-sm"
                >
                  📝 示例数据
                </button>
              </div>
            </div>

            {/* Information */}
            <div className="bg-slate-700/50 rounded-lg p-4 space-y-2">
              <div className="text-sm font-medium text-gray-300">ℹ️ 说明</div>
              <div className="text-xs text-gray-400 space-y-1">
                <p>• 输入任意正整数作为您的秘密数据</p>
                <p>• 系统会自动使用Poseidon算法计算对应的哈希值</p>
                <p>• 生成的证明将基于您的自定义数据</p>
                <p>• 原始数据仅在本地处理，确保隐私安全</p>
              </div>
            </div>
          </div>

          {/* Footer */}
          <div className="flex items-center justify-between p-6 border-t border-slate-700">
            <button
              onClick={onClose}
              disabled={isGenerating}
              className="px-4 py-2 text-gray-400 hover:text-white transition-colors disabled:opacity-50"
            >
              取消
            </button>
            <motion.button
              onClick={handleSubmit}
              disabled={isGenerating || !preImage.trim() || !!error}
              whileHover={{ scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
              className={`px-6 py-2 rounded-lg font-semibold transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-2 ${
                success
                  ? 'bg-green-600 text-white'
                  : 'bg-quantum-blue hover:bg-blue-600 text-white'
              }`}
            >
              {isGenerating ? (
                <>
                  <motion.div
                    animate={{ rotate: 360 }}
                    transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                    className="w-4 h-4 border-2 border-white border-t-transparent rounded-full"
                  />
                  <span>生成中...</span>
                </>
              ) : success ? (
                <>
                  <CheckCircle2 size={16} />
                  <span>生成成功！</span>
                </>
              ) : (
                <>
                  <Zap size={16} />
                  <span>生成数据</span>
                </>
              )}
            </motion.button>
          </div>
        </motion.div>
      </motion.div>
    </AnimatePresence>
  );
}